import { observable } from 'mobx';
import Taro from '@tarojs/taro';
import { getShopList } from '@/service/apis/shop';

function getLocalShop() {
  let defaultStore: any = null;
  try {
    let shopStr = Taro.getStorageSync('DEFAULT_SHOP');
    if (shopStr) {
      defaultStore = JSON.parse(shopStr);
    }
  } catch (err) {
    console.error('err: ', err);
  }
  return defaultStore;
}
const defaultStore = getLocalShop() || {};

const globalStore = observable({
  currentLocation: {
    locationed: false,
    lat: 0,
    lng: 0,
  },
  currentShop: {
    imageUrl: defaultStore.logo,
    store_name: defaultStore.store_name,
    address: defaultStore.store_address,
    mobile: defaultStore.mobile,
    distance: defaultStore.distance,
    status: 1,
    id: defaultStore.id,
    lat: defaultStore.lat,
    lng: defaultStore.lng,
  },
  currentVipShop: {
    imageUrl: defaultStore.logo,
    store_name: defaultStore.store_name,
    address: defaultStore.store_address,
    mobile: defaultStore.mobile,
    distance: defaultStore.distance,
    status: 1,
    id: defaultStore.id,
    lat: defaultStore.lat,
    lng: defaultStore.lng,
  },
  shopList: [],
  updateShop(shopInfo: any, type: boolean = true) {
    // type: 是否更新缓存门店
    this.currentShop = {
      ...this.currentShop,
      ...shopInfo,
      imageUrl: shopInfo.logo,
      lat: Number(shopInfo.lat),
      lng: Number(shopInfo.lng),
    };
    this.updateVipShop(this.currentShop);
    type && Taro.setStorageSync('DEFAULT_SHOP', JSON.stringify(shopInfo));
  },
  updateVipShop(shopInfo) {
    this.currentVipShop = {
      ...this.currentVipShop,
      ...shopInfo,
      imageUrl: shopInfo.logo,
      lat: Number(shopInfo.lat),
      lng: Number(shopInfo.lng),
    };
  },
  updateShopList(list: any) {
    this.shopList = list;
  },
  updateLocation(data: any) {
    this.currentLocation = {
      locationed: data.locationed,
      lng: data.lng || 0,
      lat: data.lat || 0,
    };
  },
  async getCurrentShop(flag?: boolean) {
    let _lat: any = 0;
    let _lng: any = 0;
    if (flag) {
      const { lng, lat } = await this.getLocation();
      _lat = lat;
      _lng = lng;
    }
    try {
      const { data } = await getShopList({
        lat: _lat,
        lng: _lng,
      });
      const { store_list } = data || {};
      const defaultShop = getLocalShop() || {};
      let currentShop: any = {};
      if (defaultShop.id) {
        currentShop = store_list.filter((item) => item.id === defaultShop.id)?.[0];
      }
      this.updateShop(currentShop.id ? currentShop : store_list[0], flag);
      this.updateShopList(store_list);
    } catch (err) {
      Taro.showToast({
        title: err.message,
        icon: 'none',
      });
    }
  },
  async getLocation(showAuth: any): Promise<{
    lng: number;
    lat: number;
  }> {
    return new Promise((resolve, reject) => {
      Taro.showLoading({
        title: '定位中...',
      });
      const { locationed, lng, lat } = this.currentLocation;
      if (locationed) {
        resolve({
          lng,
          lat,
        });
      } else {
        Taro.getLocation({
          type: 'gcj02',
          isHighAccuracy: true,
          success: (res) => {
            console.log('res', res);
            Taro.hideLoading();
            Taro.setStorageSync('LOCATION_AUTH', '1');
            resolve({
              lng: res.longitude,
              lat: res.latitude,
            });
            this.updateLocation({
              locationed: true,
              lng: res.longitude,
              lat: res.latitude,
            });
          },
          fail: (err: any) => {
            Taro.hideLoading();
            if (showAuth) {
              Taro.showModal({
                title: '定位授权失败',
                content: '不授权定位就无法获取当前最近门店，是否打开定位授权？',
                success: (res: any) => {
                  if (res.confirm) {
                    Taro.openSetting({
                      success: (info: any) => {
                        console.log(info);
                        if (info.authSetting['scope.userLocation']) {
                          Taro.showToast({
                            title: '获取位置授权成功，请重新点击获取地理位置',
                            icon: 'none',
                            duration: 2000,
                          });
                        }
                      },
                    });
                  }
                },
              });
            } else {
              setTimeout(() => {
                Taro.showToast({
                  title: '获取位置失败',
                  icon: 'none',
                  duration: 2000,
                });
              }, 200);
            }
            reject(err);
          },
        });
      }
    });
  },
});

export default globalStore;
